<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="shop.js"></script>
<script>
    window.onload = function () {
        showShopInfo();

    }

    /**
     * 修改商品单项总价
     * @param shopCode 商品编号
     * @param priceAllTextId 价格文本框Id
     * @param numOhj 数量输入框对象
     */
    function changePrice(shopCode, priceAllTextId, numOhj) {
        //找到要修改的对象
        console.log(shopCode + "  " + priceAllTextId + "  " + numOhj);
        let shopObj = shopArray.find(n => n.pCode == shopCode);
        //修改数组的num
        shopObj.num = numOhj.value;
        //更新单项总格
        $(priceAllTextId).innerHTML = shopObj.num * shopObj.price;
        //重新显示表格
        showShopInfo();
    }

    /**
     *删除指定标号的商品
     * @param shopCode 商品编号
     */
    function del(shopCode){
        //找到商品下标
        let index = shopArray.findIndex(n=>n.pCode==shopCode);
        //删除该商品
        shopArray.splice(index,1);

        //重新显示表格
        showShopInfo();
    }

    /**
     * 显示购物车信息
     */
    function showShopInfo() {
        let str = "";
        let totalPrice = 0;
        shopArray.forEach(n => {
            str += `<tr><td>${n.pCode}</td><td>${n.pName}</td><td>${n.price}</td>
                    <td><input type="number" min="1" value="${n.num}"onblur=changePrice(${n.pCode},"price${n.pCode}",this)></td>
                    <td id="price${n.pCode}">${n.price * n.num}</td><td><input type="button" value="移除商品" onclick="del(${n.pCode})"></td></tr>`;
            //累加价格
            totalPrice += n.price * n.num;
        });
        $("data").innerHTML = str;

        $("totalPrice").innerHTML = totalPrice;
    }

    function $(id) {
        return document.getElementById(id);
    }
</script>
<body>
<table width="60%" border="1" cellspacing="0">
    <thead>
    <tr>
        <th>商品编号</th>
        <th>商品名</th>
        <th>单价</th>
        <th>购买数量</th>
        <th>单项总价</th>
        <th>商品编号</th>
    </tr>
    </thead>
    <tbody id="data"></tbody>
</table>
购物车总价：<span id="totalPrice"></span>
</body>
</html>